package com.huifan.demo.revenue.servyou;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import net.dongliu.requests.RawResponse;
import net.dongliu.requests.Requests;

import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import cn.hutool.core.thread.ThreadUtil;

/**
 * @author: liuchenhui
 * @create: 2019-08-12 17:56
 **/
@SuppressWarnings("all")
public class ServyouService {
    // http://test.ngrok.bj17win.com/iitsservice/api/xyhq/10/911000000000000822/201909

    private static final String pre_url = "http://test.ngrok.bj17win.com/iitsservice/api/";
    private static final String appKey = "HB5A2FP837F0P5H6GHEGON3530MMH8O4IJNP32F497FC";
    private static final String appSecret = "29AEBI1FD75EE550705C9C5GGG0JI6191IICHBGB";
    private static final String nsrsbh = "911000000000000810";
    private static final String sbmm = "Qaz123456";
    private static final String areaid = "11";
    private static final String yearmo = "201910";

    public static final String CODE_0000 = "0000";
    public static final String CODE_0001 = "0001";
    public static final String CODE_0700 = "0700";

    private static final Map<String, Object> HASH_MAP = new HashMap<>();

    static {
        HASH_MAP.put("nsrsbh", nsrsbh);
        HASH_MAP.put("areaid", areaid);
        HASH_MAP.put("sdyf", yearmo);
        HASH_MAP.put("ver", "2.0.000");
        HASH_MAP.put("djxhid", "");
        HASH_MAP.put("sbmm", sbmm);
    }

    /**
     * 人员报送
     */
    public static String ryxxbs(List<Map<String, String>> data) {
        String url = "ryxxbs/".concat(areaid).concat("/").concat(nsrsbh).concat("/").concat(yearmo);
        Map<String, Object> reqBody = new HashMap<>();
        reqBody.putAll(HASH_MAP);
        reqBody.put("zrs", data.size() + "");
        reqBody.put("nsrlb", data);

        String request = request(url, reqBody, true);
        return handleReportResponse("人员报送", request);
    }

    /**
     * 人员报送状态查询
     */
    public static String ryxxbsztcx(String id) {
        String url = "ryxxbsztcx/" + id;
        return handleQueryResponse(url, null, false, "人员报送状态查询");
    }

    /**
     * 人员报送反馈
     */
    public static String ryxxfk(String id) {
        String url = "ryxxfk/".concat(id);
        String request = request(url, null, false);
        return handleReportResponse("人员报送反馈", request);

    }

    /**
     * 人员报送反馈查询
     */
    public static String ryxxfkztcx(String id) {
        String url = "ryxxfkztcx/".concat(id);
        return handleQueryResponse(url, null, false, "人员报送反馈查询");
    }

    /**
     * 专项附加扣除申报
     *
     * @id 人员报送反馈ID
     */
    public static String ryzxbs(String id, Object[] data) {
        String url = "ryzxbs/".concat(id).concat("/").concat(areaid).concat("/").concat(nsrsbh).concat("/").concat(yearmo);
        Map<String, Object> reqBody = new HashMap<>();
        reqBody.putAll(HASH_MAP);
        reqBody.put("qymc", "薪人薪事");
        reqBody.put("xzzxxx", "是");
        reqBody.put("rylb", data);

        String request = request(url, reqBody, true);
        return handleReportResponse("专项附加扣除申报", request);
    }

    /**
     * 专项附加扣除申报查询
     */
    public static String ryzxbsztcx(String id) {
        String url = "ryzxbsztcx/".concat(id);
        return handleQueryResponse(url, null, false, "专项附加扣除申报查询");
    }

    /**
     * 专项附加扣除申报反馈
     */
    public static String ryzxbsfk(String id) {
        String url = "ryzxbsfk/".concat(id);
        String request = request(url, null, false);
        return handleReportResponse("专项附加扣除申报反馈", request);
    }

    /**
     * 专项附加扣除反馈查询
     */
    public static String ryzxbsfkztcx(String id) {
        String url = "ryzxbsfkztcx/".concat(id);
        return handleQueryResponse(url, null, false, "专项附加扣除反馈查询");
    }

    /**
     * 税款计算
     *
     * @id 人员报送反馈ID
     */
    public static String skjs(String id, Map<String, Object> data) {
        String url = "skjs/".concat(yearmo).concat("/").concat(id);
        Map<String, Object> reqBody = new HashMap<>();
        reqBody.putAll(HASH_MAP);
        reqBody.put("zxzdkc", "是");
        reqBody.put("data", data);
        String request = request(url, reqBody, true);
        return handleReportResponse("税款计算", request);
    }


    /**
     * 税款计算查询
     */
    public static String skjscx(String id) {
        String url = "skjscx/".concat(id);
        return handleQueryResponse(url, null, false, "税款计算查询");
    }

    /**
     * 累计算税数据下载接口
     */
    public static String ljsssjxz(String id) {
        String url = "ljsssjxz/".concat(yearmo).concat("/").concat(id);
        Map<String, Object> reqBody = new HashMap<>();
        reqBody.putAll(HASH_MAP);
        reqBody.put("xzzxxx", "是");
        reqBody.put("xzljsj", "是");

        Map<String, Object> rylb = new HashMap<>();
        rylb.put("rylb", new Object[]{});

        reqBody.put("data", rylb);

        String request = request(url, reqBody, true);
        return handleReportResponse("累计算税数据下载接口", request);
    }


    /**
     * 累计算税数据下载查询
     */
    public static String ljsssjxzcx(String id) {
        String url = "ljsssjxzcx/".concat(id);
        return handleQueryResponse(url, null, false, "累计算税数据下载查询");
    }

    /**
     * 申报接口
     */
    public static String gssb(Map<String, Object> data) {
        String url = "gssb/".concat(areaid).concat("/").concat(nsrsbh).concat("/").concat(yearmo);
        Map<String, Object> reqBody = new HashMap<>();
        reqBody.putAll(HASH_MAP);
        reqBody.put("data", data);
        String request = request(url, reqBody, true);
        return handleReportResponse("申报接口", request);
    }

    /**
     * 申报状态查询
     */
    public static String gssbztcx(String gssbId) {
        String url = "gssbztcx/".concat(gssbId);
        return handleQueryResponse(url, null, false, "申报状态查询");
    }

    /**
     * 申报反馈接口
     */
    public static String gssbfk(String gssbId) {
        String url = "gssbfk/".concat(gssbId);
        String request = request(url, null, false);
        return handleReportResponse("申报反馈接口", request);
    }

    /**
     * 申报反馈状态查询
     */
    public static String gssbfkztcx(String gssbId) {
        String url = "gssbfkztcx/".concat(gssbId);
        return handleQueryResponse(url, null, false, "申报反馈状态查询");
    }

    /**
     * 申报数据核验
     */
    public static String gssbMxcx() {
        String url = "gssb/mxcx/".concat(areaid).concat("/").concat(nsrsbh).concat("/").concat(yearmo);
        Map<String, Object> reqBody = new HashMap<>();
        reqBody.putAll(HASH_MAP);
        String request = request(url, reqBody, true);
        return handleReportResponse("申报数据核验", request);
    }

    /**
     * 申报数据核验查询
     */
    public static String gssbMxcxCx(String gssbMxcxId) {
        String url = "gssb/mxcx/cx/".concat(gssbMxcxId);
        return handleQueryResponse(url, null, false, "申报数据核验查询");
    }

    /**
     * 申报作废接口
     */
    public static String gszf(String[] strings) {
        String url = "gszf/".concat(areaid).concat("/").concat(nsrsbh).concat("/").concat(yearmo);
        Map<String, Object> reqBody = new HashMap<>();
        reqBody.putAll(HASH_MAP);
        reqBody.put("bblb", strings);
        String request = request(url, reqBody, true);
        return handleReportResponse("申报作废接口", request);
    }

    /**
     * 作废状态查询
     */
    public static String gszfztcx(String gszfId) {
        String url = "gszfztcx/".concat(gszfId);
        return handleQueryResponse(url, null, false, "作废状态查询");
    }

    /**
     * 作废反馈接口
     */
    public static String gszffk(String gszfId) {
        String url = "gszffk/".concat(gszfId);
        String request = request(url, null, false);
        return handleReportResponse("", request);
    }

    /**
     * 作废反馈状态查询
     */
    public static String gszffkztcx(String gszfId) {
        String url = "gszffkztcx/".concat(gszfId);
        return handleQueryResponse(url, null, false, "作废反馈状态查询");
    }

    /**
     * 三方协议获取
     */
    public static String xyhq() {
        String url = "jk/xyhq/".concat(areaid).concat("/").concat(nsrsbh).concat("/").concat(yearmo);
        Map<String, Object> reqBody = new HashMap<>();
        reqBody.putAll(HASH_MAP);
        String request = request(url, reqBody, true);
        return handleReportResponse("三方协议获取", request);
    }

    /**
     * 三方协议获取查询
     */
    public static String xyhqctx(String xyhqId) {
        String url = "jk/xyhqcx/".concat(xyhqId);
        return handleQueryResponse(url, null, false, "三方协议获取查询");
    }

    /**
     * 发起缴款
     */
    public static String jk() {
        String url = "jk/".concat(areaid + "/").concat(nsrsbh + "/").concat(yearmo);
        Map<String, Object> reqBody = new HashMap<>();
        reqBody.putAll(HASH_MAP);
        reqBody.put("sdyfq", yearmo);
        reqBody.put("sdyfz", yearmo);
        String request = request(url, reqBody, true);
        return handleReportResponse("发起缴款", request);
    }

    /**
     * 发起缴款查询
     */
    public static String jkcx(String jkId) {
        String url = "jk/cx/".concat(jkId);
        return handleQueryResponse(url, null, false, "发起缴款查询");
    }


    /**
     * 缴款反馈
     */
    public static String jkfk(String jkId) {
        String url = "jk/fk/".concat(jkId);
        Map<String, Object> reqBody = new HashMap<>();
        reqBody.putAll(HASH_MAP);
        reqBody.put("sdyfq", yearmo);
        reqBody.put("sdyfz", yearmo);
        String request = request(url, reqBody, true);
        return handleReportResponse("缴款反馈", request);
    }

    /**
     * 缴款反馈查询
     */
    public static String jkfkcx(String jkId) {
        String url = "jk/fkcx/".concat(jkId);
        return handleQueryResponse(url, null, false, "缴款反馈查询");
    }

    /**
     * ===========================================================================================================
     */

    private static String request(String url, Map<String, Object> reqbody, boolean isPost) {

        String fullUrl = pre_url.concat(url);

        Map<String, Object> headers = new HashMap<>(9);
        long timestamp = System.currentTimeMillis();
        headers.put("appkey", appKey);
        headers.put("timestamp", timestamp);
        headers.put("version", "1.0");
        headers.put("signature", ShaUtil.getSHA256(appSecret, appKey + timestamp + appSecret).toUpperCase());
        headers.put("xReqNonce", UUID.randomUUID());
        headers.put("product_id", "");
        headers.put("product_version", "V0.49");
        headers.put("Content-Type", "application/json");
        headers.put("Accept", "application/json");
//        System.out.println(JSON.toJSONString(headers));
        RawResponse response = null;
        if (isPost) {
            response = Requests.post(fullUrl).headers(headers).body(JSON.toJSONString(reqbody)).verify(false).timeout(600000).send();
        } else {
            response = Requests.get(fullUrl).headers(headers).verify(false).timeout(600000).send();
        }
        return response != null ? response.readToText() : "";
    }

    private static String handleReportResponse(String content, String request) {
        JSONObject jsonObject = JSON.parseObject(request);
        String code = jsonObject.getString("code");
        String status = jsonObject.getString("status");
        if (!StringUtils.isBlank(status)) {
            System.out.println("服务错误,msg=" + jsonObject.getString("message"));
            throw new RuntimeException();
        }
        if (CODE_0000.equals(code)) {
            return request;
        } else {
            System.out.println(content + "异常:" + jsonObject.getString("msg") + "|数据 data:" + jsonObject.getString("data") + "|====code:" + code);
            throw new RuntimeException();
        }
    }

    private static String handleQueryResponse(String url, Map<String, Object> reqbody, boolean isPost, String content) {
        while (true) {
            ThreadUtil.sleep(1000);
            String request = request(url, reqbody, isPost);
            JSONObject jsonObject = JSON.parseObject(request);
            String code = jsonObject.getString("code");
            String status = jsonObject.getString("status");
            if (!StringUtils.isBlank(status)) {
                System.out.println("服务错误,msg=" + jsonObject.getString("message"));
                throw new RuntimeException();
            }
            if (CODE_0000.equals(code)) {
                return request;
            } else if (CODE_0700.equals(code)) {
                System.out.println("任务处理中，再次查询");
                System.out.println(content + "异常:" + jsonObject.getString("msg") + "|数据 data:" + jsonObject.getString("data") + "|====code:" + code);
                continue;
            } else {
                System.out.println(content + "异常:" + jsonObject.getString("msg") + "|数据 data:" + jsonObject.getString("data") + "|====code:" + code);
                throw new RuntimeException();
            }
        }
    }
}